package com.dotlrn.mobile.nfc;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.dotlrn.mobile.R;

public class DotLRNNFCContextualLearningDiscoverActivity extends Activity {

	public static final String PREFS_NAME = "MyPrefsFile";
	static final int ACTIVITY_TIMEOUT_MS = 1 * 1000;
	private WebView dotLRNWebView;
	private String globalURL;

	private NfcAdapter mAdapter;
	private byte[] tagId;
	private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1',
			(byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
			(byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B',
			(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F' };
	private boolean nfcRedirect;
	private String dotlrnURL;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mAdapter = NfcAdapter.getDefaultAdapter(this);
		if (!mAdapter.isEnabled()) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Please enable you NFC Adaptar")
					.setCancelable(false)
					.setPositiveButton("back",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									finish();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		} else {

			// Restore preferences
			SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
			dotlrnURL = settings.getString("dotlrnURL", "");

			if (dotlrnURL.toLowerCase().indexOf("http://") == -1) {

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(
						"Please set a valid URL for your dotLRN site")
						.setCancelable(false)
						.setPositiveButton("back",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										finish();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			} else {
				setContentView(R.layout.discover);

				dotLRNWebView = (WebView) findViewById(R.id.dotlrn_webview);
				DotLRNWebViewClient dotLRNWebViewClient = new DotLRNWebViewClient();
				dotLRNWebView.setWebViewClient(dotLRNWebViewClient);
				dotLRNWebView.getSettings().setJavaScriptEnabled(true);
				dotLRNWebView.getSettings().setPluginState(PluginState.ON);
				dotLRNWebView.getSettings().setCacheMode(
						WebSettings.LOAD_NO_CACHE);
				dotLRNWebView.loadUrl(dotlrnURL + "/register/logout");
				dotLRNWebView.loadUrl(dotlrnURL + "/dotlrn/m-courses");
			}
		}
		nfcRedirect = false;
	}

	void resolveIntent(Intent intent) {

		MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(),
				R.raw.blip);
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mediaPlayer) {
				mediaPlayer.release();
			}
		});

		mediaPlayer.start();

		Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		tagId = myTag.getId();

		if (nfcRedirect) {

			String claId = Uri.parse(globalURL).getQueryParameter("claid");
			String baseUrl = "http://" + Uri.parse(globalURL).getHost() + ":"
					+ Uri.parse(globalURL).getPort()
					+ Uri.parse(globalURL).getPath();

			dotLRNWebView.loadUrl(baseUrl + "?claid=" + claId + "&tag_key="
					+ getHexString(tagId, tagId.length));
		}
	}

	private class DotLRNWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			if (Uri.parse(url).getHost().equals(Uri.parse(dotlrnURL).getHost())) {
				// This is my web site, so do not override; let my WebView load
				// the page
				globalURL = url;

				if (url.indexOf("cla-object-discover") != -1) {
					nfcRedirect = true;
				} else if (url.indexOf("cla-object-discover") == -1) {
					nfcRedirect = false;
				}

				view.loadUrl(url);
				return false;
			}
			// Otherwise, the link is not for a page on my site, so launch
			// another Activity that handles URLs
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			startActivity(intent);
			return true;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("go back to main menu?")
					.setCancelable(false)
					.setPositiveButton("yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dotLRNWebView.loadUrl(dotlrnURL + "/register/logout");
									DotLRNNFCContextualLearningDiscoverActivity.this
											.finish();
								}
							}).setNegativeButton("no", null);
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onResume() {

		super.onResume();
		IntentFilter discovery = new IntentFilter(
				NfcAdapter.ACTION_TAG_DISCOVERED);
		IntentFilter[] tagFilters = new IntentFilter[] { discovery };
		Intent i = new Intent(this, getClass())
				.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
						| Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
		mAdapter.enableForegroundDispatch(this, pi, tagFilters, null);
	}

	@Override
	public void onPause() {
		super.onPause();
		mAdapter.disableForegroundDispatch(this);
	}

	@Override
	public void onNewIntent(Intent intent) {
		resolveIntent(intent);
	}

	public static String getHexString(byte[] raw, int len) {
		byte[] hex = new byte[2 * len];
		int index = 0;
		int pos = 0;
		for (byte b : raw) {
			if (pos >= len)
				break;
			pos++;
			int v = b & 0xFF;
			hex[index++] = HEX_CHAR_TABLE[v >>> 4];
			hex[index++] = HEX_CHAR_TABLE[v & 0xF];
		}
		return new String(hex);
	}

}
